﻿using System.Threading;
using System.Threading.Tasks;

namespace OmniKits.Async
{
    public abstract class RunJobMixed<T> : RunJobAsync<T>, IRunJob
        where T : class, ICanStart, ICanWait, ICanStartAsync, ICanWaitAsync
    {
        protected virtual bool Run(bool wait)
        {
            var old = _Job;
            if (old != null)
            {
                old.Start();
                if (wait)
                    old.Wait();
                return false;
            }

            var job = GetJob();
            old = Interlocked.CompareExchange(ref _Job, job, null);
            if (old != null)
            {
                old.Start();
                if (wait)
                    old.Wait();
                return false;
            }

            try
            {
                job.Start();
                if (wait)
                    old.Wait();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, null, job);
                throw;
            }
        }

        public virtual bool Start()
            => Run(false);
        public virtual bool Run()
            => Run(true);

        public virtual bool Wait()
        {
            var job = _Job;
            if (job == null)
                return false;
            return job.Wait();
        }
    }
    public abstract class RunJobCanStopMixed<T> : RunJobMixed<T>, IRunJobCanStop, IRunJobCanStopAsync
        where T : class, ICanStart, ICanWait, ICanStop, ICanStartAsync, ICanWaitAsync, ICanStopAsync
    {
        public virtual bool Stop()
        {
            var job = _Job;
            if (job == null)
                return false;
            job = Interlocked.Exchange(ref _Job, null);
            if (job == null)
                return false;

            try
            {
                job.Stop();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, job, null);
                throw;
            }
        }
        public virtual async Task<bool> StopAsync()
        {
            var job = _Job;
            if (job == null)
                return false;
            job = Interlocked.Exchange(ref _Job, null);
            if (job == null)
                return false;

            try
            {
                await job.StopAsync();
                return true;
            }
            catch
            {
                Interlocked.CompareExchange(ref _Job, job, null);
                throw;
            }
        }
    }
}
